import { prisma } from '@/lib/prisma';
import { DestinationGrid } from './DestinationGrid';
import { getServerSession } from 'next-auth';
import { authOptions } from '../api/auth/[...nextauth]/route';
import { Tabs } from './Tabs';

async function getDestinations() {
  const session = await getServerSession(authOptions);
  
  // 获取官方推荐目的地
  const officialDestinations = await prisma.destination.findMany({
    where: { 
      isOfficial: true 
    },
    include: {
      _count: {
        select: { activities: true }
      },
      savedBy: true
    },
    orderBy: {
      createdAt: 'desc'
    }
  });

  // 如果用户已登录，获取用户的目的地
  const userDestinations = session?.user?.id ? await prisma.destination.findMany({
    where: { 
      OR: [
        { createdById: session.user.id },
        { savedBy: { some: { id: session.user.id } } }
      ]
    },
    include: {
      _count: {
        select: { activities: true }
      },
      savedBy: true
    },
    orderBy: {
      createdAt: 'desc'
    }
  }) : [];

  return {
    officialDestinations,
    userDestinations
  };
}

export default async function DestinationsPage() {
  const { officialDestinations, userDestinations } = await getDestinations();

  return (
    <div className="max-w-7xl mx-auto py-8 px-4 sm:px-6 lg:px-8">
      <div className="flex justify-between items-center mb-8">
        <h1 className="text-3xl font-bold text-blue-900">目的地</h1>
        <a
          href="/destinations/new"
          className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-blue-600 hover:bg-blue-700 transition-colors duration-200"
        >
          <svg 
            className="w-5 h-5 mr-2" 
            fill="none" 
            stroke="currentColor" 
            viewBox="0 0 24 24"
          >
            <path 
              strokeLinecap="round" 
              strokeLinejoin="round" 
              strokeWidth={2} 
              d="M12 4v16m8-8H4" 
            />
          </svg>
          添加目的地
        </a>
      </div>

      <Tabs
        officialDestinations={officialDestinations}
        userDestinations={userDestinations}
      />
    </div>
  );
}